package com.faithbj.controller.dataTransfer;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.faithbj.common.model.CheckTotal;
import com.faithbj.common.model.DataExportLog;
import com.faithbj.common.model.User;
import com.faithbj.common.web.controller.BaseController;
import com.faithbj.constant.Constant;
import com.faithbj.process.ProcessApplicationService;
import com.faithbj.process.State;
import com.faithbj.process.TaskModel;
import com.faithbj.service.CompareService;
import com.faithbj.service.DataTransferService;
import com.faithbj.support.compare.AjaxResult;
import com.faithbj.support.updownload.FileUploadHandler;

/**
 * 数据导入导出
 * 
 * @author chen liu
 */
@Controller
public class DataTransferController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(DataTransferController.class);

    private static final long serialVersionUID = 3502990015134594157L;
    private static final int FIRST = 1;
    private static final int LIMIT = Integer.MAX_VALUE;
    @Resource
    private FileUploadHandler uploadHandler;
    @Resource
    private DataTransferService dataTransferService;

    @Resource
    private CompareService compareService;

    @Resource
    private ProcessApplicationService processApplicationService;

    /**
     * 导出数据文件(data.zip)
     * 
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/transfer/export")
    public void exportData(HttpServletRequest request, HttpServletResponse response) {
        User user = super.getLoginUser();
        if (user == null) {
            printHtml(response, "登录用户为空!");
            return;
        }

        // 通过jbpm查询得到进行到信息核实的check_total列表作为导出范围
        List<TaskModel> tasks = processApplicationService.listAvailableTasksWithContentByUserAndState(
                State.VERIFICATION, FIRST, LIMIT);
        List<String> checkTotalIds = new ArrayList<String>();
        if (tasks != null) {
            for (TaskModel task : tasks) {
                CheckTotal checkTotal = task.getCheckTotal();
                if (checkTotal != null) {
                    checkTotalIds.add(checkTotal.getId());
                }
            }
        }
        if(checkTotalIds.isEmpty()){
            printHtml(response, "没有需要导出的数据文件!");
            return;
        }
            
        // 导出数据库表并将数据文件和证明材料打包成export.zip
        boolean flag = dataTransferService.exportDBFiles(checkTotalIds);
        if (flag == false) {
            logger.error("数据文件导出出错!");
            printHtml(response, "数据文件导出出错!");
            return;
        }

        // 执行文件下载
        String dataZipFilePath = getExportFilePath();
        String fileDisplayName = Constant.EXP_ZIP_FILE;
        response.reset();
        response.setContentType("application/zip");
        response.addHeader("Content-Disposition", "attachment;filename=" + fileDisplayName);

        OutputStream output = null;
        FileInputStream input = null;
        try {
            output = response.getOutputStream();
            input = new FileInputStream(dataZipFilePath);
            byte[] b = new byte[1024];
            int i = 0;
            while ((i = input.read(b)) > 0) {
                output.write(b, 0, i);
            }
            output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        // 写入数据导出记录表
        DataExportLog exportLog = new DataExportLog();
        exportLog.setUserId(user.getId());
        compareService.saveOrUpdateExportLog(exportLog);
    }

    /**
     * 导入数据文件
     * 
     * @param request
     * @param model
     * @return AjaxResult
     */
    @RequestMapping("/transfer/import")
    @ResponseBody
    public AjaxResult importData(HttpServletRequest request) {
        // 文件上传
        AjaxResult result = new AjaxResult(true);
        boolean flag = false;
        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile file = multipartRequest.getFile("importFile");

            // 检测扩展名
            String fileName = file.getOriginalFilename();
            if (fileName != null) {
                fileName = fileName.toLowerCase();
                int lastIndex = fileName.lastIndexOf(".");
                if (lastIndex != -1) {
                    String fileExt = fileName.substring(lastIndex, fileName.length());
                    if (StringUtils.hasLength(fileExt) && ".zip".equals(fileExt)) {
                        flag = uploadHandler.uploadByFilePath(file, getImportFilePath());
                    }
                }
            }
        }
        if (flag == false) {
            result.setResult(false);
            result.addMsg("数据文件上传失败!");
            return result;
        }
        
        // 调用shell脚本解压import.zip 执行导入
        return null;
    }

    private String getExportFilePath() {
        return Constant.EXP_FILE_PATH_PREFIX + Constant.EXP_ZIP_FILE;
    }
    
    private String getImportFilePath(){
        return Constant.IMP_FILE_PATH_PREFIX + Constant.EXP_ZIP_FILE;
    }
    
    private void printHtml(HttpServletResponse res, String message){
        try {
            PrintStream ps = new PrintStream(res.getOutputStream());
            res.setCharacterEncoding("utf-8");
            res.setContentType("text/html;charset=utf-8");
            ps.print(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
